﻿using ProtoBuf.Message;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Yunchang.NetworkLayer;

public class ChessPackageItem : MonoBehaviour
{
    public TextureKit packageIcon;
    public Text packageName,coinLable;
    public GroupSpriteKit coinImage;
    public UGUIToggle toggles;

    public Transform heroRoot;
    public HeroItem heroPrefab;
    public GameObject buyBtn, gettedBtn,herosRoot,bgRoot;
    public ScrollRect scrollRect;
    public GridLayoutGroup group;

    private Dictionary<int, HeroItem> heroItem = new Dictionary<int, HeroItem>();

    private Action<string> onClick;
    private int packageId = 0;
    private HeroExtPackage itemData;
    public void InitItem(HeroExtPackage itemData,Action<string> onClick)
    {
        this.itemData = itemData;
        gameObject.SetActive(true);
        toggles.onValueChangedEvent = OnClickPackgageItem;
        group.childAlignment = /*itemData.heros.Count <= 5 ? TextAnchor.MiddleCenter : */TextAnchor.MiddleLeft;
        RefreshItem(itemData);
        this.onClick = onClick;
    }

    public void RefreshItem(HeroExtPackage itemData)
    {
        packageId = itemData.packageId;
        packageIcon.TextureName = itemData.packageIcon;
        packageName.text = itemData.packageName;
        coinLable.text = itemData.coinItemBase.num.ToString();
        coinImage.SetSpriteName(CommonMethod.GetCoinUIIcon((ItemBaseType)itemData.coinItemBase.type));

        buyBtn.SetActive(!itemData.isGetted);
        gettedBtn.SetActive(itemData.isGetted);

        HeroItem script;
        foreach (var item in itemData.heros)
        {
            if (!heroItem.ContainsKey(item.heroId))
            {
                script = Instantiate<HeroItem>(heroPrefab, heroRoot);
            }
            else
            {
                script = heroItem[item.heroId];
            }
            script.Refresh(item);
            heroItem[item.heroId] = script;
        }
    }

    public void OnClickPackgageItem(object obj,bool value)
    {
        if (herosRoot.activeSelf == true && !value)
        {
            scrollRect.enabled = true;
        }

        herosRoot.SetActive(value);
        bgRoot.SetActive(value);

        if (value)
        {
            if (onClick != null)
            {
                onClick(itemData.packageBg);
            }
            scrollRect.enabled = false;
            
            Invoke("ScrollRectFunc",0.1f);
        }
        
    }

    private void ScrollRectFunc()
    {
        UI.UIScrollRectMethod.ScrollToItem(scrollRect, gameObject, UI.UIScrollRectMethod.ScrollRectAutoMoveType.Horizontal);
    }

    public void OnClickHeroBuyButtom()
    {
        NetworkDriver.Instance.SendSocketBlock(OpDefine.CSAutoChessBuyPacket, 
            new CSAutoChessBuyPacket() { packetId = packageId },OpDefine.SCAutoChessBuyPacket);
    }
}
